<?php
/**
 * @package PWE.modele
 * @author Gmax <gmaxfr78@gmail.com>
 */
class modele_galerie extends modele {
    protected static $_table = 'galerie';
    private $_id;
    private $_title;
    private $_template;
    private $_category_id;
    private $_category;
    private $_permalien;
    private $_medias = array();
    private $_mediasDatas = array();
    
    public $type = 'galerie';
    
    function __construct($id=null){
        if($id!==null){
            $this->_id = $id;
            $this->_constructObject();
        }
    }
    private function _constructObject(){
        $sqlQuery = 'SELECT ';
        $sqlQuery .= 't.* ';
        $sqlQuery .= 'FROM '.self::getTable().' as t ';
        $sqlQuery .= 'WHERE t.id='.$this->getId().' ';
        $sqlQuery .= 'LIMIT 1';
        
        $datas = $this->_getOneResult($sqlQuery);
        if($datas){
            $this->_id = $datas['id'];
            $this->_title =  $datas['title'];
            $this->_template =  $datas['template'];
            $this->_category_id =  $datas['category_id'];
            $this->_category = new modele_category($this->getCategoryId());
            $this->_permalien = new modele_permalien('galerie',$this->getId());
        }
    }
    
    /**
     * 
     * @return int
     */
    public function getId(){
        return $this->_id;
    }
    
    /**
     * renvoi le titre de la galerie
     * @param boolean $input
     * @return string
     */
    public function getTitle($input=false){
        if($input)return $this->inputFormat($this->_title);
        else return $this->outputFormat($this->_title);
    }
    /**
     * 
     * @return \modele_permalien
     */
    public function getPermalien(){
        if($this->_permalien === null) $this->_permalien = new modele_permalien('galerie');
        return $this->_permalien;
    }
    
    /**
     * 
     * @return string
     */
    public function getUrl(){
        $urlCategory = $this->getCategory()->getUrl();
        return $urlCategory.$this->getPermalien()->getLien();
    }
    public function getTranslatedUrl($lang=''){
        $urlCategory = $this->getCategory()->getTranslatedUrl($lang);
        return $urlCategory.$this->getPermalien()->getTranslatedLien($lang);
    }
    
    /**
     * 
     * @return string
     */
    public function getTitreSEO(){
        return $this->getPermalien()->getTitre();
    }
    
    /**
     * 
     * @return string
     */
    public function getDescriptionSEO() {
        return $this->getPermalien()->getDescription();
    }
    
    /**
     * 
     * @return int
     */
    public function getCategoryId(){
        return $this->_category_id;
    }
    /**
     * renvoi la category parent
     * @return \modele_category
     */
    public function getCategory(){
        if($this->_category === null) $this->_category = new modele_category();
        return $this->_category;
    }
    
    /**
     * renvoi le template pour affichage front
     * @return string
     */
    public function getTemplate(){
        return $this->_template;
    }
    
    /**
     * revoi la liste des objet media
     * @return \modele_media
     */
    public function getMedias(){
        if(!isset($this->_medias)||count($this->_medias)<1){
            $sqlQueryMedias = 'SELECT * FROM '.PWE::getPrefixBdd().'galerie_media WHERE galerie_id='.$this->getId().' ORDER BY `order`';
            $listeMedias = $this->_getResults($sqlQueryMedias);
            if($listeMedias){
                $retour = array();
                foreach($listeMedias['results'] as $result){
                    $media = new modele_media($result['media_id']);
                    if($media->getId()>0){
                        $retour[] = $media;
                    }else{
                        $this->removeMedia($result['media_id']);
                    }
                }
                $this->_medias = $retour;
            }
        }
        return $this->_medias;
    }
    
    /**
     * retourne la liste des mediaDatas
     * @param boolean $input
     * @return array
     */
    public function getMediasDatas($input){
        if(count($this->_mediasDatas)==0){
            foreach($this->getMedias() as $k=>$media){
                $this->_mediasDatas[$k] = $media->getDatas($input);
                $this->_mediasDatas[$k]['order'] = $k;
            }
        }
        return $this->_mediasDatas;
    }
    public function getDatas($input=false){
        $data = array(
            'id' => $this->getId(),
            'title' => $this->getTitle($input),
            'template' => $this->getTemplate(),
            'titre_seo'=>$this->getPermalien()->getTitre($input),
            'description_seo'=>$this->getPermalien()->getDescription($input),
            'permalien'=>$this->getPermalien()->getLien(),
            'url'=>$this->getUrl(),
            'category_id' => $this->getCategoryId(),
            'medias' => $this->getMediasDatas($input)
        );
        return $data;
    }
    public function setDatas($datas){
        foreach($datas as $k=>$v){
            if(substr($k, 0, 1) !== '_') $k = '_'.$k;
            if($k != '_id' && property_exists(get_class($this),$k)){
                $this->$k = $v;
            }
        }
        $this->getCategory()->setDatas($datas);
        $this->getPermalien()->setDatas($datas);
        return true;
    }
    
    /**
     * ajoute un media à la galerie
     * @param int $mediaId
     * @return array() [success,order]
     */
    public function addMedia($mediaId){
        $order = count($this->getMedias());
        
        $sqlQueryGalerieMedia = 'INSERT INTO '.PWE::getPrefixBdd().'galerie_media ';
        $sqlQueryGalerieMedia .= '(galerie_id,media_id,`order`) ';
        $sqlQueryGalerieMedia .= 'VALUES ('.$this->getId().','.$mediaId.','.$order.')';
        
        bdd_sql::doSql($sqlQueryGalerieMedia,false);
        
        $this->_medias = null;
        $this->_mediasDatas = null;
        
        return array('success'=>true,'order'=>$order);
    }
    
    /**
     * supprime un media de la galerie
     * @param int $mediaId
     * @return array [success]
     */
    public function removeMedia($mediaId){
        $sqlQueryGalerieMedia = 'DELETE FROM '.PWE::getPrefixBdd().'galerie_media WHERE galerie_id='.$this->getId().' AND media_id='.$mediaId;
        bdd_sql::doSql($sqlQueryGalerieMedia,false);
        
        $this->_medias = null;
        $this->_mediasDatas = null;
        
        return array('success'=>true);
    }
    
    /**
     * modifie l'ordre d'un media dans la galerie
     * @param int $mediaId
     * @param int $order
     * @return array [success]
     */
    public function changeOrder($mediaId, $order){
        $query = 'UPDATE '.PWE::getPrefixBdd().'galerie_media SET `order`='.$order.' WHERE galerie_id='.$this->getId().' AND media_id='.$mediaId;
        bdd_sql::doSql($query,false);
        
        $this->_medias = null;
        $this->_mediasDatas = null;
        
        return array('success'=>true);
    }
    
    public function save() {
        if(modele_user::isConnectedAdmin()){
            $sqlQueryGalerie = 'INSERT INTO '.self::getTable().' ';
            $sqlQueryGalerie .= '(title,';
            if($this->getCategoryId()>0) $sqlQueryGalerie .= 'category_id,';
            $sqlQueryGalerie .= 'template) ';
            $sqlQueryGalerie .= 'VALUES ("'.$this->getTitle(true).'",';
            if($this->getCategoryId()>0) $sqlQueryGalerie .= $this->getCategoryId().',';
            $sqlQueryGalerie .= '"'.$this->getTemplate().'")';

            bdd_sql::doSql($sqlQueryGalerie,false);
            $this->_id = bdd_sql::getLastInsertId();

            //permalien
            $this->getPermalien()->setDatas(array('_modele_id'=>$this->_id));
            $this->getPermalien()->save();

            return array('success'=>true,'datas'=>$this->getDatas());
        }else{
            return array('success'=>false,'datas'=>array());
        }
    }
    
    public function update(){
        if(modele_user::isConnectedAdmin()){
            $sqlQueryGalerie = 'UPDATE '.self::getTable().' SET title="'.$this->getTitle(true).'", ';
            if($this->getCategoryId()>0) $sqlQueryGalerie .= 'category_id='.$this->getCategoryId().', ';
            $sqlQueryGalerie .= 'template="'.$this->getTemplate().'" ';
            $sqlQueryGalerie .= 'WHERE id='.$this->_id.' LIMIT 1';
            bdd_sql::doSql($sqlQueryGalerie,false);

            //permalien
            $this->getPermalien()->update();

            return array('success'=>true,'datas'=>$this->getDatas());
        }else{
            return array('success'=>false,'datas'=>array());
        }
    }
    public function delete() {
        if(modele_user::isConnectedAdmin()){
            if(count($this->getMedias())>0){
                foreach ($this->getMedias() as $media){
                    $this->removeMedia($media->getId());
                }
            }
            $this->getPermalien()->delete();
            $sqlDelete = 'DELETE FROM '.self::getTable().' WHERE id='.$this->_id;
            bdd_sql::doSql($sqlDelete,false);
            return array('success'=>true,'datas'=>array());
        }else{
            return array('success'=>false,'datas'=>array());
        }
    }
    /* methodes statiques */
    /**
     * 
     * @return string
     */
    public static function getTable(){
        return PWE::getPrefixBdd().self::$_table;
    }
    
    public static function getListe($start = 0,$limit = 0){
        $sqlQuery = 'SELECT id FROM '.self::getTable().' ORDER BY id DESC';
        if($limit>0){
            $sqlQuery .=  ' LIMIT '.$start.','.$limit;
        }
        $retour = array();
        $results = bdd_sql::doSql($sqlQuery,true);
        if($results['count']>0){
            foreach($results['results'] as $galerieData){
                $retour[] = new modele_galerie($galerieData['id']);
            }
        }
        return $retour;
    }
    /**
     * 
     * @param int $categoryId
     * @param int $start
     * @param int $limit
     * @return \modele_galerie array
     */
    public static function findByCategory($categoryId,$start=0,$limit=0){
        $sqlQuery = 'SELECT id FROM '.self::getTable().' WHERE category_id='.$categoryId.' ORDER BY id DESC';
        if($limit>0){
            $sqlQuery .=  ' LIMIT '.$start.','.$limit;
        }
        $retour = array();
        $results = bdd_sql::doSql($sqlQuery,true);
        if($results['count']>0){
            foreach($results['results'] as $galerieData){
                $retour[] = new modele_galerie($galerieData['id']);
            }
        }
        return $retour;
    }
}
?>